import BaseAudioManager from "../cfw/audio/BaseAudioManager";
import TSMap from "../cfw/struct/TSMap";

/**
 * AudioSource 和 cc.audioEngine 最大的区别是，AudioSource 不可以用来播放背景音乐。
 *AudioSource 是作为组件挂载在场景的各种节点上的，所以它可能同时会有多个。而背景音乐的底层播放接口不支持多音轨，
 *同一时刻只能播放一个。所以背景音乐需要用 cc.audioEngine.playMusic 来切换，而 AudioSource 应该用来播放短音效
 *所以 我们只使用AudioEngine 就好了。
 */
export default class SoundManager extends BaseAudioManager {


    private soundMap: TSMap<string, number> = new TSMap();

    play(name: string, canMulply: boolean = false) {

        super.play(name, canMulply);
    }
    
    getMaxNum(){
        return  cc.audioEngine.getMaxAudioInstance();
    }
    /**
     * 
     * @param name 
     * @param res 
     * @param canMulply 不可以同时播放两个以上
     */
    add(name, res, canMulply) {
        // cc.log(' play sound name ',name,' canMulply ',canMulply)
        if (!canMulply) {
            if (this.soundMap.size() > 0) {
                return;
            }
            this.soundMap.set(name, 1)
            let audioId = cc.audioEngine.playEffect(res, false);
            this.sourcePool.set(name, audioId);
            cc.audioEngine.setFinishCallback(audioId, this.over.bind(this, name));
        } else {
            let audioId = cc.audioEngine.playEffect(res, false);
            this.sourcePool.set(name, audioId);
        }
    }

    over(name: string) {
        // console.log('over name ==================   ', name)
        this.soundMap.remove(name)
    }

    pause(name: string) {
        let audioId = this.sourcePool.get(name);
        if (audioId) {
            cc.audioEngine.pauseEffect(audioId);
        }
    }

    resume(name: string) {
        let audioId = this.sourcePool.get(name);
        if (audioId) {
            cc.audioEngine.resumeEffect(audioId);
        }
    }

    stop(name: string) {
        if (this.soundMap.has(name)) {
            let audioId = this.sourcePool.get(name);
            if (audioId) {
                cc.audioEngine.stopEffect(audioId);
                this.sourcePool.delete(name);
            }
        }

    }

    setVolume(count: number) {
        cc.audioEngine.setEffectsVolume(count);
    }

    stopAll() {
        this.soundMap.forEach((key, value) => {
            this.stop(key);
        })
        this.soundMap.clear();
    }

    isPlaying() {
        return false;
    }


    clear() {
        // console.log(' clear ==================   ')
        this.sourcePool.forEach((key, audioId) => {
            // console.log(' key ',key)
            // console.log('clear audioId ==================   ',audioId)
            cc.audioEngine.stopEffect(audioId);
        })
        this.sourcePool.clear();
        // cc.audioEngine.stopAllEffects();
    }

}